package com.msk.common.wechatV3.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.msk.common.wechatV3.base.Pay;
import com.msk.common.wechatV3.pojo.combined.bo.closeorder.CloseOrderBo;
import com.msk.common.wechatV3.pojo.combined.bo.placeorder.CombinedPayBo;
import com.msk.common.wechatV3.pojo.combined.vo.notify.CombinedNotfyVo;
import com.msk.common.wechatV3.pojo.combined.vo.notify.NotifyParameters;
import com.msk.common.wechatV3.pojo.combined.vo.selectorder.SelectComBinedOrderVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class WxComBinedPayV3Util extends Pay {
    private static final Logger logger = LoggerFactory.getLogger(WxComBinedPayV3Util.class);

    private static final String url_prex = "https://api.mch.weixin.qq.com/";

    /**
     * 合单支付下单
     *
     * @param url                请求地址（只需传入域名之后的路由地址）
     * @param combinedPayBo      请求体 json字符串 此参数与微信官方文档一致
     * @param mercId             商户ID
     * @param serial_no          证书序列号
     * @param privateKeyFilePath 私钥的路径
     * @return
     * @throws Exception
     */
    public static Map<String,String> v3ComBinedPayGet(String url, CombinedPayBo combinedPayBo, String mercId, String serial_no, String privateKeyFilePath) throws Exception {
        Object body = postRequest(url_prex, url, mercId, serial_no, privateKeyFilePath, JSONUtil.toJsonStr(combinedPayBo));
        Map<String,String> map = new HashMap<>();
        JSONObject jsonObject = JSONUtil.parseObj(body.toString());
        map.put("code",jsonObject.getStr("code"));
        map.put("message",jsonObject.getStr("message"));
        switch (url) {
            case "v3/combine-transactions/app":
            case "v3/combine-transactions/jsapi":
                String prepay_id = jsonObject.getStr("prepay_id");
                map.put("prepay_id",prepay_id);
                return map;
            case "v3/combine-transactions/native":
                String code_url = jsonObject.getStr("code_url");
                map.put("code_url",code_url);
                return map;
            case "v3/combine-transactions/h5":
                String h5_url = jsonObject.getStr("h5_url");
                map.put("h5_url",h5_url);
                return map;
            default:
                return null;
        }
    }

    /**
     * 处理微信合单支付异步回调
     *
     * @param request
     * @param response
     * @param privateKey 32的秘钥
     * @return 支付的订单号
     */
    public static Map<String,Object> notify(HttpServletRequest request, HttpServletResponse response, String privateKey) throws Exception {
        String result = readData(request);
        logger.info("微信小程序回调返回参数："+result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        Map<String,Object> refundMap = new HashMap<>();
        refundMap.put("code",jsonObject.get("code"));
        refundMap.put("message",jsonObject.get("message"));
        NotifyParameters notifyParameters = JSONUtil.toBean(jsonObject, NotifyParameters.class);
        // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
        String plainText = verifyNotify(result, privateKey);
        //发送消息通知微信
        //sendMessage(response, plainText);
        CombinedNotfyVo combinedNotfyVo = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            combinedNotfyVo = mapper.readValue(plainText,
                    new TypeReference<CombinedNotfyVo>() {
                    });
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if(null != combinedNotfyVo){
            notifyParameters.getResource().setCombinedNotfyVo(combinedNotfyVo);
        }
        refundMap.put("notifyParameters",notifyParameters);
        refundMap.put("plainText",plainText);
        return refundMap;
    }

    /**
     * 查询合单支付订单信息
     *
     * @param mchid 商户ID
     * @return 订单支付成功之后的详细信息
     * @throws Exception
     */
    public static SelectComBinedOrderVo selectOrder(String url, String mchid, String serial_no, String privateKeyFilePath) throws Exception {
        Object body = getRequest(url_prex, url, mchid, serial_no, privateKeyFilePath);
        SelectComBinedOrderVo selectComBinedOrderVo = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            selectComBinedOrderVo = mapper.readValue(body.toString(),
                    new TypeReference<SelectComBinedOrderVo>() {
                    });
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return selectComBinedOrderVo;
    }

    /**
     * 关闭未支付的合单支付的订单
     *
     * @param url                请求域名
     * @param mchid              商户号
     * @param serial_no          证书序列号
     * @param privateKeyFilePath 证书秘钥地址
     * @return 订单关闭成功，无任何返回
     * @throws Exception
     */
    public static String closeCombinedOrder(String url, String mchid, String serial_no, String privateKeyFilePath, CloseOrderBo closeOrderBo) throws Exception {
        Object body = postRequest(url_prex, url, mchid, serial_no, privateKeyFilePath, JSONUtil.toJsonStr(closeOrderBo));
        return body.toString();
    }

}
